@{
    ViewData["Title"] = "生产计划详情";
    Layout = "_Layout"; // 关联公共布局
}

<div class="container-fluid">
    <!-- 详情头部信息 -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h3 class="card-title" id="planTitle">生产计划详情</h3>
                            <p class="card-text">
                                创建人: <span id="createUser">--</span> | 创建时间: <span id="createTime">--</span>
                                | 负责人: <span id="responsibleUser">--</span> | 修改时间: <span id="modifyTime">--</span>
                            </p>
                        </div>
                        <div>
                            <button type="button" class="btn btn-primary me-2" id="editButton">编辑</button>
                            <button type="button" class="btn btn-danger me-2" id="deleteButton">删除</button>
                            <button type="button" class="btn btn-secondary" id="printButton">打印</button>
                            <button type="button" class="btn btn-outline-secondary" id="closeButton">关闭</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 标签页导航 -->
    <div class="row mb-4">
        <div class="col-md-12">
            <ul class="nav nav-tabs" id="detailTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="planInfo-tab" data-bs-toggle="tab" data-bs-target="#planInfo" type="button" role="tab" aria-controls="planInfo" aria-selected="true">生产计划信息</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="operationLog-tab" data-bs-toggle="tab" data-bs-target="#operationLog" type="button" role="tab" aria-controls="operationLog" aria-selected="false">操作记录</button>
                </li>
            </ul>
        </div>
    </div>

    <!-- 标签页内容 -->
    <div class="tab-content" id="detailTabsContent">
        <!-- 生产计划信息标签页 -->
        <div class="tab-pane fade show active" id="planInfo" role="tabpanel" aria-labelledby="planInfo-tab">
            <div class="card">
                <div class="card-body">
                    <form id="productionPlanForm" class="row g-3">
                        <div class="col-md-4">
                            <label for="Plan_Number" class="form-label">计划编号</label>
                            <input type="text" class="form-control" id="Plan_Number" name="Plan_Number" readonly>
                        </div>
                        <div class="col-md-4">
                            <label for="Plan_Name" class="form-label">计划名称</label>
                            <input type="text" class="form-control" id="Plan_Name" name="Plan_Name" readonly>
                        </div>
                        <div class="col-md-4">
                            <label for="Source_Type" class="form-label">来源类型</label>
                            <select class="form-select" id="Source_Type" name="Source_Type" disabled>
                                <option value="0">自主生产</option>
                                <option value="1">销售订单</option>
                                <option value="2">库存补充</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="Order_Number" class="form-label">订单编号</label>
                            <input type="text" class="form-control" id="Order_Number" name="Order_Number" readonly>
                        </div>
                        <div class="col-md-4">
                            <label for="State" class="form-label">状态</label>
                            <select class="form-select" id="State" name="State" disabled>
                                <option value="0">未开始</option>
                                <option value="1">进行中</option>
                                <option value="2">已完成</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="Start_Time" class="form-label">计划开工时间</label>
                            <input type="datetime-local" class="form-control" id="Start_Time" name="Start_Time" readonly>
                        </div>
                        <div class="col-md-4">
                            <label for="Completion_Time" class="form-label">计划完工时间</label>
                            <input type="datetime-local" class="form-control" id="Completion_Time" name="Completion_Time" readonly>
                        </div>
                        <div class="col-md-4">
                            <label for="Requirement_Date" class="form-label">需求日期</label>
                            <input type="datetime-local" class="form-control" id="Requirement_Date" name="Requirement_Date" readonly>
                        </div>
                        <div class="col-md-12">
                            <label for="Notes" class="form-label">备注</label>
                            <textarea class="form-control" id="Notes" name="Notes" rows="3" readonly></textarea>
                        </div>
                    </form>

                    <!-- 产品信息展示区域 -->
                    <div class="mt-6">
                        <h4 class="mb-3">产品信息</h4>
                        <div id="productInfoContainer">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>产品名称</th>
                                        <th>规格型号</th>
                                        <th>单位</th>
                                        <th>单价(未税)</th>
                                        <th>数量</th>
                                    </tr>
                                </thead>
                                <tbody id="productListTableBody">
                                    <!-- 产品信息将通过JS动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作记录标签页 -->
        <div class="tab-pane fade" id="operationLog" role="tabpanel" aria-labelledby="operationLog-tab">
            <div class="card">
                <div class="card-body">
                    <!-- 操作记录表格 -->
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th scope="col"><input type="checkbox"></th>
                                <th scope="col">序号</th>
                                <th scope="col">操作人</th>
                                <th scope="col">操作时间</th>
                                <th scope="col">操作内容</th>
                            </tr>
                        </thead>
                        <tbody id="operationLogTableBody">
                            <!-- 操作记录数据将通过JS动态加载 -->
                        </tbody>
                    </table>

                    <!-- 分页控件 -->
                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <div class="text-muted">共 <span id="totalCount">30</span> 项数据</div>
                        <div class="d-flex align-items-center">
                            <select id="pageSize" class="form-select form-select-sm me-2" style="width: auto;">
                                <option value="5">5条/页</option>
                                <option value="10">10条/页</option>
                                <option value="20">20条/页</option>
                                <option value="50">50条/页</option>
                            </select>
                            <div class="pagination">
                                <button class="btn btn-sm btn-outline-secondary me-1" disabled>&lt;</button>
                                <button class="btn btn-sm btn-primary me-1">1</button>
                                <button class="btn btn-sm btn-outline-secondary me-1">2</button>
                                <button class="btn btn-sm btn-outline-secondary me-1">3</button>
                                <button class="btn btn-sm btn-outline-secondary me-1">4</button>
                                <button class="btn btn-sm btn-outline-secondary me-1">5</button>
                                <button class="btn btn-sm btn-outline-secondary">&gt;</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部按钮 -->
    <div class="row mt-4">
        <div class="col-md-12 text-center">
            <button type="button" class="btn btn-outline-secondary" id="bottomCloseButton">关闭</button>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        // 获取URL中的计划ID
        function getPlanId() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('id') || 0;
        }

        // 加载生产计划详情
        function loadProductionPlanDetail() {
            const planId = getPlanId();
            if (!planId) {
                alert('无法获取生产计划ID');
                return;
            }

            // 实际项目中应该使用AJAX从API获取数据
            $.ajax({
                url: 'http://localhost:5104/api/WorkOrder/ProductionPlanDetailGet?Id=' + planId,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    console.log('API返回数据:', response); // 添加调试信息

                    // 先检查response是否存在
                    if (!response) {
                        alert('获取生产计划详情失败：返回数据为空');
                        loadMockData(); // 加载模拟数据作为后备
                        return;
                    }

                    // 兼容不同的成功响应格式
                    let data;
                    if (response.code === 200 && response.data) {
                        data = response.data;
                    } else if (typeof response === 'object') {
                        // 如果直接返回数据对象，没有code和data结构
                        data = response;
                    } else {
                        alert('获取生产计划详情失败：' + (response?.message || '未知错误'));
                        loadMockData(); // 加载模拟数据作为后备
                        return;
                    }

                    console.log('处理后的数据:', data); // 添加调试信息

                    // 从data中提取plan对象，如果不存在则使用空对象
                    const planData = data.plan || {};

                    // 填充表单数据 - 使用plan对象中的下划线格式字段名
                    document.getElementById('Plan_Number').value = planData.plan_Number || '';
                    document.getElementById('Plan_Name').value = planData.plan_Name || '';
                    document.getElementById('Source_Type').value = planData.source_Type || 0;
                    document.getElementById('Order_Number').value = planData.order_Number || '';
                    document.getElementById('State').value = planData.state || 0;

                    // 处理日期格式，使用plan对象中的下划线格式字段名
                    if (planData.start_Time) {
                        try {
                            const startTime = new Date(planData.start_Time);
                            if (!isNaN(startTime.getTime())) {
                                document.getElementById('Start_Time').value = startTime.toISOString().slice(0, 16);
                            }
                        } catch (e) {
                            console.error('解析开始时间失败:', e);
                        }
                    }

                    if (planData.completion_Time) {
                        try {
                            const completionTime = new Date(planData.completion_Time);
                            if (!isNaN(completionTime.getTime())) {
                                document.getElementById('Completion_Time').value = completionTime.toISOString().slice(0, 16);
                            }
                        } catch (e) {
                            console.error('解析完成时间失败:', e);
                        }
                    }

                    if (planData.requirement_Date) {
                        try {
                            const requirementDate = new Date(planData.requirement_Date);
                            if (!isNaN(requirementDate.getTime())) {
                                document.getElementById('Requirement_Date').value = requirementDate.toISOString().slice(0, 16);
                            }
                        } catch (e) {
                            console.error('解析需求日期失败:', e);
                        }
                    }

                    document.getElementById('Notes').value = planData.notes || '';

                    // 填充头部信息
                    document.getElementById('planTitle').textContent = planData.plan_Name || '生产计划详情';
                    document.getElementById('createUser').textContent = planData.createUserId ? '用户' + planData.createUserId : '--';
                    document.getElementById('createTime').textContent = planData.createTime ? formatDateTime(planData.createTime) : '--';
                    document.getElementById('responsibleUser').textContent = planData.upDataUserId ? '用户' + planData.upDataUserId : '--';
                    document.getElementById('modifyTime').textContent = planData.upDataTime ? formatDateTime(planData.upDataTime) : '--';

                    // 填充产品信息表格 - 使用与API返回匹配的product数组
                    const productListTableBody = document.getElementById('productListTableBody');
                    productListTableBody.innerHTML = '';

                    // 使用API返回的product数组
                    const productList = data.product || [];
                    if (Array.isArray(productList) && productList.length > 0) {
                        productList.forEach(product => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${product.product_Name || ''}</td>
                                <td>${product.specification || ''}</td>
                                <td>${product.unit || ''}</td>
                                <td>${product.untaxed_Price || product.untaxedPrice || 0}</td>
                                <td>${product.quantity || 0}</td>
                            `;
                            productListTableBody.appendChild(row);
                        });
                    } else {
                        const noDataRow = document.createElement('tr');
                        noDataRow.innerHTML = `
                            <td colspan="5" class="text-center text-muted">暂无产品信息</td>
                        `;
                        productListTableBody.appendChild(noDataRow);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('API调用失败：', status, error);
                    console.error('响应内容：', xhr.responseText);
                    alert('获取生产计划详情失败，请检查网络连接或联系管理员');

                    // 加载失败时使用模拟数据
                    loadMockData();
                }
            });
        }

        // 其他函数保持不变
        // 加载模拟数据（备用）
        function loadMockData() {
            const mockData = {
                plan_Number: "7894657845",
                planName: "物料一计划",
                sourceType: 1,
                order_Number: "销售订单1",
                quantity_Orders: 1,
                product_Id: 2,
                planned_quantity: 200,
                start_Time: "2025-08-15T08:15:07.8266667",
                completion_Time: "2025-08-15T08:15:07.8266667",
                requirement_Date: "2025-08-15T08:15:07.8266667",
                state: 1,
                notes: "无",
                createUser: "admin",
                createTime: "2025-08-15T12:12:45",
                updateTime: null,
                productList: [
                    {
                        product_Name: "滴露芳芬",
                        specification: "DF-8867",
                        unit: "个",
                        untaxed_Price: 10,
                        quantity: 100
                    }
                ]
            };

            // 填充表单数据
            document.getElementById('Plan_Number').value = mockData.plan_Number || '';
            document.getElementById('Plan_Name').value = mockData.planName || '';
            document.getElementById('Source_Type').value = mockData.sourceType || 0;
            document.getElementById('Order_Number').value = mockData.order_Number || '';
            document.getElementById('State').value = mockData.state || 0;

            // 处理日期格式
            if (mockData.start_Time) {
                const startTime = new Date(mockData.start_Time);
                document.getElementById('Start_Time').value = startTime.toISOString().slice(0, 16);
            }

            if (mockData.completion_Time) {
                const completionTime = new Date(mockData.completion_Time);
                document.getElementById('Completion_Time').value = completionTime.toISOString().slice(0, 16);
            }

            if (mockData.requirement_Date) {
                const requirementDate = new Date(mockData.requirement_Date);
                document.getElementById('Requirement_Date').value = requirementDate.toISOString().slice(0, 16);
            }

            document.getElementById('Notes').value = mockData.notes || '';

            // 填充头部信息
            document.getElementById('planTitle').textContent = mockData.planName || '生产计划详情';
            document.getElementById('createUser').textContent = mockData.createUser || '--';
            document.getElementById('createTime').textContent = mockData.createTime ? formatDateTime(mockData.createTime) : '--';
            document.getElementById('responsibleUser').textContent = mockData.createUser || '--';
            document.getElementById('modifyTime').textContent = mockData.updateTime ? formatDateTime(mockData.updateTime) : '--';

            // 填充产品信息表格
            const productListTableBody = document.getElementById('productListTableBody');
            productListTableBody.innerHTML = '';

            if (mockData.productList && mockData.productList.length > 0) {
                mockData.productList.forEach(product => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${product.product_Name || ''}</td>
                        <td>${product.specification || ''}</td>
                        <td>${product.unit || ''}</td>
                        <td>${product.untaxed_Price || 0}</td>
                        <td>${product.quantity || 0}</td>
                    `;
                    productListTableBody.appendChild(row);
                });
            } else {
                const noDataRow = document.createElement('tr');
                noDataRow.innerHTML = `
                    <td colspan="5" class="text-center text-muted">暂无产品信息</td>
                `;
                productListTableBody.appendChild(noDataRow);
            }
        }

        // 日期时间格式化工具函数
        function formatDateTime(dateTimeString) {
            if (!dateTimeString) return '';
            try {
                const date = new Date(dateTimeString);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            } catch (e) {
                return dateTimeString;
            }
        }

        // 加载操作记录
        function loadOperationLog() {
            const planId = getPlanId();
            if (!planId) {
                return;
            }

            // 模拟操作记录数据
            const mockOperationLogs = [
                { id: 1, operator: "孙十二", operationTime: "2024-06-27 19:15:59", operationContent: "新增产品" },
                { id: 2, operator: "黄一一", operationTime: "2024-06-27 18:30:08", operationContent: "上传文件" },
                { id: 3, operator: "郑十", operationTime: "2024-06-27 17:05:47", operationContent: "修改" },
                { id: 4, operator: "吴九", operationTime: "2024-06-27 16:10:33", operationContent: "删除" },
                { id: 5, operator: "周八", operationTime: "2024-06-27 15:20:14", operationContent: "上传文件" }
            ];

            // 填充操作记录表格
            const tableBody = document.getElementById('operationLogTableBody');
            tableBody.innerHTML = '';

            mockOperationLogs.forEach((log, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox"></td>
                    <td>${index + 1}</td>
                    <td>${log.operator}</td>
                    <td>${log.operationTime}</td>
                    <td>${log.operationContent}</td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 初始化页面
        $(document).ready(function() {
            // 确保页面加载完成后再执行
            setTimeout(function() {
                loadProductionPlanDetail();
                loadOperationLog();
            }, 100);

            // 编辑按钮点击事件
            $('#editButton').click(function() {
                const planId = getPlanId();
                window.location.href = `/Home/ProductionPlan?id=${planId}&mode=edit`;
            });

            // 删除按钮点击事件
            $('#deleteButton').click(function() {
                if (confirm('确定要删除此生产计划吗？')) {
                    const planId = getPlanId();
                    alert('删除操作已触发，计划ID：' + planId);
                }
            });

            // 打印按钮点击事件
            $('#printButton').click(function() {
                window.print();
            });

            // 关闭按钮点击事件
            $('#closeButton, #bottomCloseButton').click(function() {
                window.location.href = '/Home/ProductionPlanList';
            });

            // 标签页切换事件
            $('#detailTabs button').on('shown.bs.tab', function(e) {
                const tabId = e.target.getAttribute('data-bs-target');
                if (tabId === '#operationLog') {
                    loadOperationLog();
                }
            });
        });
    </script>
}